package com.tusuo.stds.ui.resetpassword;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.andreabaccega.formedittextvalidator.SameValueValidator;
import com.andreabaccega.widget.FormEditText;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.FadeEnter.FadeEnter;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.tusuo.stds.R;
import com.tusuo.stds.ui.ToolbarOwner;
import com.tusuo.stds.ui.BaseToolbarActivity;
import com.tusuo.stds.ui.register.RegisterActivity;
import com.tusuo.stds.util.Utils;
import com.tusuo.stds.util.validator.CaptchaValidator;
import com.tusuo.stds.util.validator.MobilePhoneNumberValidator;
import com.tusuo.stds.util.validator.PasswordValidator;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.StringRes;

import myandroid.library.util.ApplicationHelper;

@EActivity(R.layout.activity_reset_password)
public class ResetPasswordActivity extends BaseToolbarActivity<ResetPasswordView, ResetPasswordPresenter>
                                implements ResetPasswordView {

    @ViewById(R.id.tv_msg)
    TextView tvMsg;

    // 借助一个空的layout在LinearLayout中显示分割线
    @ViewById(R.id.reset_password_layout_placeholder)
    RelativeLayout layoutPlaceholder;

    @ViewById(R.id.reset_password_layout_mobile_num)
    RelativeLayout layoutMobileNum;
    @ViewById(R.id.et_mobile_num)
    FormEditText etMobileNum;

    @ViewById(R.id.reset_password_layout_password)
    RelativeLayout layoutPassword;
    @ViewById(R.id.et_password)
    FormEditText etPassword;
    @ViewById(R.id.reset_password_layout_confirm_password)
    RelativeLayout layoutConfirmPassword;
    @ViewById(R.id.et_confirm_password)
    FormEditText etConfirmPassword;

    @ViewById(R.id.reset_password_layout_captcha)
    RelativeLayout layoutCaptcha;
    @ViewById(R.id.et_captcha)
    FormEditText etCaptcha;
    @ViewById(R.id.reset_password_layout_sms)
    RelativeLayout layoutSms;
    @ViewById(R.id.tv_sms)
    TextView tvSms;

    @ViewById(R.id.reset_password_btn_next)
    Button btnNext;
    @ViewById(R.id.reset_password_btn_get_captcha)
    Button btnGetCaptcha;

    @StringRes(R.string.toolbar_title_reset_password)
    String toolbarTitleReset;
    @StringRes(R.string.toolbar_title_set_password)
    String toolbarTitleSet;
    @StringRes(R.string.err_msg_mobile_number)
    String strErrMsgMobileNumber;
    @StringRes(R.string.err_msg_password)
    String strErrMsgPassword;
    @StringRes(R.string.err_msg_confirm_password)
    String strErrMsgConfirmPassword;
    @StringRes(R.string.err_msg_captcha)
    String strErrMsgCaptcha;
    @StringRes(R.string.reset_password_btn_next)
    String strNext;
    @StringRes(R.string.reset_password_btn_done)
    String strDone;
    @StringRes(R.string.btn_captcha)
    String strCaptcha;

    @ColorRes(R.color.colorPrimary)
    int toolbarBgColor;
    @ColorRes(R.color.textColorPrimary)
    int toolbarTextColor;

    private int mStep;

    private NormalDialog mDialog;

    private Step1EditTextChangedListener step1EditTextChangedListener;

    @AfterViews
    void afterViews() {
        setupUI(this, toolbarBgColor, toolbarTextColor);

        ToolbarOwner.Config config = new ToolbarOwner.Config(toolbarTitleReset, true, R.drawable.ic_back_dark, null);
        mToolbarOwner.setConfig(config);

        step1EditTextChangedListener = new Step1EditTextChangedListener();

        setupStep1();

        etMobileNum.addValidator(new MobilePhoneNumberValidator(strErrMsgMobileNumber));
        etPassword.addValidator(new PasswordValidator(strErrMsgPassword));
        etConfirmPassword.addValidator(new SameValueValidator(etPassword, strErrMsgConfirmPassword));
        etCaptcha.addValidator(new CaptchaValidator(strErrMsgCaptcha));

        initDialog();

        ApplicationHelper.getInstance().addActivity(this);
    }

    private void setupStep1() {
        mStep = 1;

        layoutMobileNum.setVisibility(View.VISIBLE);
        layoutPassword.setVisibility(View.GONE);
        layoutConfirmPassword.setVisibility(View.GONE);
        layoutCaptcha.setVisibility(View.GONE);
        layoutSms.setVisibility(View.GONE);
        layoutPlaceholder.setVisibility(View.VISIBLE);

        btnNext.setText(strNext);
        btnNext.setEnabled(false);

        etMobileNum.addTextChangedListener(step1EditTextChangedListener);
    }

    private void setupStep2() {
        mStep = 2;

        ToolbarOwner.Config config = new ToolbarOwner.Config(toolbarTitleReset, true, R.drawable.ic_back_dark, null);
        mToolbarOwner.setConfig(config);

        layoutMobileNum.setVisibility(View.GONE);
        layoutPassword.setVisibility(View.GONE);
        layoutConfirmPassword.setVisibility(View.GONE);
        layoutCaptcha.setVisibility(View.VISIBLE);
        layoutSms.setVisibility(View.VISIBLE);
        layoutPlaceholder.setVisibility(View.GONE);

        etMobileNum.removeTextChangedListener(step1EditTextChangedListener);
        btnNext.setText(strNext);

        btnGetCaptcha.setText(strCaptcha);
        btnGetCaptcha.setEnabled(true);
    }

    private void setupStep3() {
        mStep = 3;

        ToolbarOwner.Config config = new ToolbarOwner.Config(toolbarTitleSet, true, R.drawable.ic_back_dark, null);
        mToolbarOwner.setConfig(config);

        layoutMobileNum.setVisibility(View.GONE);
        layoutPassword.setVisibility(View.VISIBLE);
        layoutConfirmPassword.setVisibility(View.VISIBLE);
        layoutCaptcha.setVisibility(View.GONE);
        layoutSms.setVisibility(View.GONE);
        layoutPlaceholder.setVisibility(View.VISIBLE);
        btnNext.setText(strDone);
    }

    @Override
    public void onBackPressed() {
        switch (mStep) {
            case 1:
                super.onBackPressed();
                break;
            case 2:
                if (presenter.canGoBack()) {
                    setupStep1();
                } else {
                    showTipDialog();
                }
                break;
            case 3:
                setupStep2();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (mDialog != null) {
            mDialog.superDismiss();
            mDialog = null;
        }
        super.onDestroy();
    }

    @NonNull
    @Override
    public ResetPasswordPresenter createPresenter() {
        return new ResetPasswordPresenter(this);
    }

    @Override
    public void setCaptchaBtnEnabled(boolean enabled) {
        btnGetCaptcha.setEnabled(enabled);
    }

    @Override
    public void setCaptchaBtnText(String text) {
        btnGetCaptcha.setText(text);
    }

    @Override
    public void showErrMsg(String text) {
        tvMsg.setText(text);
        tvMsg.setTextColor(Color.RED);
    }

    @Override
    public void showSlogan() {
        tvMsg.setText(getString(R.string.slogan));
        tvMsg.setTextColor(Color.WHITE);
    }

    @Override
    public void setSmsText(String text) {
        tvSms.setText(text);
    }

    @Override
    public void showTipDialog() {
        mDialog.show();
    }

    private void initDialog() {
        BaseAnimatorSet bas_in = new FadeEnter();
        BaseAnimatorSet bas_out = new FadeExit();

        mDialog = new NormalDialog(this);
        mDialog.isTitleShow(false)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content(getString(R.string.dlg_title_captcha))
                .contentGravity(Gravity.CENTER)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText("返回上一步", "确定")
                .btnTextSize(15.5f, 15.5f)
                .btnTextColor(Color.parseColor("#333333"), Color.parseColor("#0092FF"))
                .widthScale(0.7f)
                .showAnim(bas_in)
                .dismissAnim(bas_out);

        mDialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        mDialog.dismiss();
                        presenter.allowGoBack();
                        setupStep1();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        mDialog.dismiss();
                    }
                }
        );
    }

    @Click(R.id.reset_password_btn_get_captcha)
    void clickGettingCaptchaBtn() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        if (!etMobileNum.testValidity()) {
            presenter.showErrMsg(strErrMsgMobileNumber);
            return;
        }

        presenter.getCaptcha(etMobileNum.getText().toString());
    }

    @Click(R.id.reset_password_btn_next)
    void clickNextBtn() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        // 强制隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

        switch (mStep) {
            case 1:
                if (!etMobileNum.testValidity()) {
                    presenter.showErrMsg(strErrMsgMobileNumber);
                    return;
                }
                setupStep2();
                presenter.getCaptcha(etMobileNum.getText().toString());
                break;
            case 2:
                if (!etCaptcha.testValidity()) {
                    presenter.showErrMsg(strErrMsgCaptcha);
                    return;
                }
                setupStep3();
                presenter.allowGoBack();
                break;
            case 3:
                if (!etPassword.testValidity()) {
                    presenter.showErrMsg(strErrMsgPassword);
                    return;
                }
                if (!etConfirmPassword.testValidity()) {
                    presenter.showErrMsg(strErrMsgConfirmPassword);
                    return;
                }
                presenter.setPassword(etMobileNum.getText().toString(),
                        etPassword.getText().toString(),
                        etCaptcha.getText().toString());
                break;

        }
    }

    private class Step1EditTextChangedListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (etMobileNum.getText().length() > 0) {
                btnNext.setBackgroundResource(R.drawable.selector_theme_button);
                btnNext.setEnabled(true);
            } else {
                btnNext.setBackgroundResource(R.drawable.shape_theme_button_disabled);
                btnNext.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    }
}
